/**
 * Created by zxh on 14-5-13.
 */

ms = ms || {};

ms.UIHelper = (function() {

    var widgetEvent = {
        widgetClass: ccui.Widget,
        events:["on%name%TouchBegan", "on%name%TouchMoved", "on%name%TouchEnded"],
        addEventListener: "addTouchEventListener"
    };

    var widgetEvents = [
        //Button
        {
            widgetClass: ccui.Button,
            events: widgetEvent.events,
            addEventListener: widgetEvent.addEventListener
        },

        //ImageView
        {
            widgetClass: ccui.ImageView,
            events: widgetEvent.events,
            addEventListener: widgetEvent.addEventListener
        },

        //TextFiled
        {
            widgetClass: ccui.TextField,
            events: ["on%name%AttachWithIME", "on%name%DetachWithIME", "on%name%InsertText", "on%name%DeleteBackward"],
            addEventListener: "addEventListenerTextField"
        },

        //CheckBox
        {
            widgetClass: ccui.CheckBox,
            events: ["on%name%Selected", "on%name%Unselected"],
            addEventListener: "addEventListenerCheckBox"
        },

        //ListView
        {
            widgetClass: ccui.ListView,
            events:["on%name%SelectedItem"],
            addEventListener: "addEventListenerListView"
        },

        //PageView
        {
            widgetClass: ccui.PageView,
            events:["on%name%Event"],
            addEventListener: "addEventListenerPageView"
        },

        //Panel
        {
            widgetClass: ccui.Layout,
            events: widgetEvent.events,
            addEventListener: widgetEvent.addEventListener
        },

        //ScrollView
        {
            widgetClass: ccui.ScrollView,
            events: ["on%name%Event"],
            addEventListener: "addEventListenerScrollView"
        },

        //BMFont
        {
            widgetClass: ccui.TextBMFont,
            events: widgetEvent.events,
            addEventListener: widgetEvent.addEventListener
        },
    ];

    var bindWidget = function(widget, target) {
        //找到事件
        var bindWidgetEvent = _.find(widgetEvents, function(widgetEvent) {
            if (widget instanceof widgetEvent.widgetClass) {
                return widgetEvent;
            }
        });

        //绑定事件
        if (bindWidgetEvent) {
            registerWidgetEvent(target, widget, bindWidgetEvent);
        }
    };

    //注册控件事件函数
    var registerWidgetEvent = function(target, widget, widgetEvent) {
        var name = widget.getName();

        var eventsArray = _.map(widgetEvent.events, function(eventName) {
            var newName = name[1].toUpperCase() + name.slice(2);
            var funcName = eventName.replace("%name%", newName);

            return funcName;
        });


        var eventName, isBindEvent;
        for (var i = 0; i < eventsArray.length; i++) {
            eventName = eventsArray[i];

            if (_.isFunction(target[eventName])) {
                isBindEvent = true;
                break;
            }
        }

        var eventFunc = function(sender, type) {
            var funcName = eventsArray[type];
            var callBack = target[funcName];
            if (callBack) {
                //cc.log("callBack: " + funcName);
                return callBack.call(target, sender);
            }
        };

        if (isBindEvent) {
            widget.setTouchEnabled(true);
            var addEventListener = widgetEvent.addEventListener;
           // cc.log("bind widgetName " + name);
            cc.assert(widget[addEventListener], "error: " + addEventListener + " function is not exist!");
            widget[addEventListener](eventFunc, target);
        }
    };

    //bind成员变量
    var bindMembers = function(rootWidget, target) {
        var widgetName,
            children = rootWidget.getChildren();

        _.each(children, function(widget) {
            widgetName = widget.getName();

            //控件名存在，绑定到target上
            if (widgetName && widgetName[0] === "_") {
                target[widgetName] = widget;
                bindWidget(widget, target);
            }

            //如果还有子节点，递归进去
            if (widget.getChildrenCount()) {
                bindMembers(widget, target);
            }
        });
    };


    //加载UI文件
    var loadWidgetFile = function(jsonFile, target) {
        if (!jsonFile || !target) {
            cc.log("error: jsonfile or target is null");
            return;
        }

        var root = ccs.uiReader.widgetFromJsonFile(jsonFile);
        if (!root) {
            cc.log(jsonFile + " create error");
            return ;
        }

        //适配根Panel居中
        //this.adaptToCenter(root);

        if (target.addChild) {
            target.addChild(root);
        }

        //适配分辨率
//        root.setContentSize(cc.director.getWinSize());

        if (!target.rootNode) {
            target.rootNode = root;
        }

        bindMembers(root, target);
        return root;
    };

    return {loadWidgetFile: loadWidgetFile};
})();